package com.springdoor.wx.api.service.impl;

import com.springdoor.wx.api.entity.ResultCli;
import com.springdoor.wx.api.entity.WxUser;
import com.springdoor.wx.api.mapper.WxUserMapper;
import com.springdoor.wx.api.service.WxUserService;
import com.springdoor.wx.core.domain.entity.LoginUser;
import com.springdoor.wx.core.token.TokenService;
import com.springdoor.wx.utils.ServletUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class WxUserServiceImpl implements WxUserService {

    @Autowired
    private WxUserMapper userMapper;

    @Autowired
    private TokenService tokenService;

    @Override
    public WxUser findUserByOpenid(String openId) {
        return userMapper.findUserByOpenid(openId);
    }

    @Override
    public List<WxUser> selectWxUserList(WxUser wxUser) {
        return userMapper.selectWxUserList(wxUser);
    }

    @Override
    public int insertWxUser(WxUser wxUser) {
        return userMapper.insertWxUser(wxUser);
    }

    @Override
    public int updateWxUser(WxUser wxUser) {
        return userMapper.updateWxUser(wxUser);
    }

    @Override
    public int updateWxUser(LoginUser loginUser, WxUser wxUser) {
        int i = userMapper.updateWxUser(wxUser);
        WxUser user = userMapper.findUserByOpenid(loginUser.getUser().getOpenid());
        loginUser.setUser(user);
        loginUser.setUserName(user.getUserName());
        tokenService.refreshToken(loginUser);
        return i;
    }

    @Override
    public ResultCli fetchUserInfo() {
        WxUser user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        if (user == null) {
            return null;
        }
        ResultCli result = new ResultCli();
        result.setNickName(user.getUserName());
        result.setAvatarUrl(user.getAvatar());
        result.setEmail(user.getEmail());
        result.setPhone(user.getPhone());
        result.setGender(user.getSex());
        result.setUserType(user.getUserType());
        return result;
    }
}
